package master.photo.controller.security

import org.springframework.beans.factory.annotation.Autowired;

import master.photo.service.AppUserService;
import master.photo.domain.security.AppUser;

class LoginController {
	
	@Autowired
	AppUserService appUserService;
	
	def index = {
		redirect action: auth, params: params
	}
	
	/**
	 * Show the login page.
	 */
	def auth = {
		
		nocache response
		
		String view  = 'auth'
		String postUrl = "${request.contextPath}/login/openIdAuthenticate"
		
		render view: view, model: [postUrl: postUrl]
	}
	
	/**
	 * Form submit action to start an OpenID authentication.
	 */
	def openIdAuthenticate = {
		String userId = params['j_username'];
		session['J_USERNAME'] = userId;
		String userpass = params['j_password'];
		
		AppUser user = appUserService.findByUsername(userId);
		if (user && user.username == userpass) {
			session['USER_LOGGED_IN'] = user;
			redirect controller: 'profile', action: 'show', id: user.profile.id
		} else {
			redirect action: authfail, params: params
		}
	}	
	
	/**
	 * login failed
	 */
	def authfail = {
		def username = session['J_USERNAME']
		def msg = "Wrong login credentials for username ${username}"
		
		flash.message = msg
		redirect action: auth, params: params
	}
	
	/** cache controls */
	private void nocache(response) {
		response.setHeader('Cache-Control', 'no-cache') // HTTP 1.1
		response.addDateHeader('Expires', 0)
		response.setDateHeader('max-age', 0)
		response.setIntHeader ('Expires', -1) //prevents caching at the proxy server
		response.addHeader('cache-Control', 'private') //IE5.x only
	}
}
